# 导入必要的编程库，创建计算图，加载数据集
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from sklearn import datasets
from tensorflow.python.framework import ops

# start the tensorflow session
ops.reset_default_graph()
# initialize interactive session
sess = tf.Session()
# iris_data, iris_tar = datasets.load_iris(True)
iris = datasets.load_iris()

# print("iris_data: ", iris_data)
# print("iris_target: ", iris_tar)

# print("iris.data: ", iris.data)

x_vals = np.array([x[3] for x in iris.data])
y_vals = np.array([y[0] for y in iris.data])
# print("x_vals: ", x_vals)
# print("y_vals: ", y_vals)

# 声明学习率、批量大小、占位符和模型变量
learning_rate = .05
batch_size = 25
x_data = tf.placeholder(shape=[None, 1], dtype=tf.float32)
y_target = tf.placeholder(shape=[None, 1], dtype=tf.float32)
A = tf.Variable(tf.random_normal(shape=[1, 1]))
b = tf.Variable(tf.random_normal(shape=[1, 1]))

# 增加线性模型, y = Ax + b
model_output = tf.add(tf.matmul(x_data, A), b)

# 声明L2损失函数，其为批量损失的平均值
# 初始化变量，声明优化器，学习率设置为0.05
loss = tf.reduce_mean(tf.square(y_target - model_output))
init = tf.global_variables_initializer()
sess.run(init)
my_opt = tf.train.GradientDescentOptimizer(learning_rate)
train_step = my_opt.minimize(loss)

# 迭代遍历，并在随机选择的批量数据上进行模型训练
# 迭代100次，每25次迭代输出变量值和损失值
# 保存每次迭代的损失值，将其用于后续的可视化
loss_vec = []
for i in range(100):
    rand_index = np.random.choice(len(x_vals), size=batch_size)
    # print("[x_vals[rand_index]] = ", [x_vals[rand_index]])
    # print("[y_vals[rand_index]] = ", [y_vals[rand_index]])
    rand_x = np.transpose([x_vals[rand_index]])  # 转置，行变列
    rand_y = np.transpose([y_vals[rand_index]])
    # print("rand_x: ", rand_x)
    # print("rand_y: ", rand_y)
    sess.run(train_step, feed_dict={x_data: rand_x, y_target: rand_y})
    temp_loss = sess.run(loss, feed_dict={x_data: rand_x, y_target: rand_y})
    loss_vec.append(temp_loss)
    if (i + 1) % 25 == 0:
        print('Step #' + str(i) + ' A = ' + str(sess.run(A)) + ' b = ' + str(sess.run(b)))
        print('Loss = ' + str(temp_loss))

# 抽取系数，创建最佳拟合直线
[slope] = sess.run(A)
[y_intercept] = sess.run(b)
print('[slope]: ', slope)
print('[y_intercept]: ', y_intercept)
best_fit = []
for i in x_vals:
    best_fit.append(slope * i + y_intercept)

# 绘图
plt.plot(x_vals, y_vals, 'o', label='Data Points')
plt.plot(x_vals, best_fit, 'r-', label='Best fit line', linewidth=3)
plt.legend(loc='upper left')
plt.title('Sepal Length vs Petal Width')
plt.xlabel('Petal Width')
plt.ylabel('Sepal Length')
plt.show()
plt.plot(loss_vec, 'k-')
plt.title('L2 Loss per Generation')
plt.xlabel('Generation')
plt.ylabel('L2 Loss')
plt.show()
